/**
 * 固定资产管理系统 - 时尚简约主题交互增强
 * 版本：v6.0.0 - Minimal Fashion Edition
 * 描述：现代化时尚简约主题的交互效果和动画
 */

class MinimalThemeEnhancer {
    constructor() {
        this.isLoaded = false;
        this.sidebarState = 'normal'; // 'normal', 'expanded', 'collapsed'
        this.init();
    }

    init() {
        console.log('🎨 时尚简约主题初始化中...');
        
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.setupTheme();
            });
        } else {
            this.setupTheme();
        }
    }

    setupTheme() {
        // 初始化各种功能
        this.setupAnimations();
        this.setupInteractions();
        this.setupMobileMenu();
        this.setupKeyboardShortcuts();
        this.setupSmoothScrolling();
        this.setupLoadingStates();
        this.setupSearchEnhancements();
        this.setupNavigationHighlight();
        this.setupSidebarControls(); // 新增：菜单栏控制
        this.setupResponsiveLayout(); // 新增：响应式布局
        this.applyFlickerSuppression(); // 在日志/模态上下文抑制动画
        
        this.isLoaded = true;
        console.log(' 时尚简约主题已激活');
        
        // 触发主题加载完成事件
        this.triggerThemeLoadedEvent();
    }

    /**
     * 在日志/模态上下文抑制动画和过渡，降低闪烁
     * 与 admin_custom.js 的全局抑制保持兼容
     */
    applyFlickerSuppression() {
        const ensureSuppressionStyles = () => {
            if (document.getElementById('ui-suppress-style-minimal')) return;
            const style = document.createElement('style');
            style.id = 'ui-suppress-style-minimal';
            style.type = 'text/css';
            style.textContent = `
              .suppress-animations *, html.suppress-animations * {
                transition: none !important;
                animation: none !important;
                scroll-behavior: auto !important;
                will-change: auto !important;
              }
              .suppress-animations .card:hover,
              html.suppress-animations .card:hover,
              .suppress-animations .dropdown-item:hover,
              html.suppress-animations .dropdown-item:hover {
                transform: none !important;
                box-shadow: none !important;
              }
              /* 确保模态与遮罩在抑制时不做过渡，减少开关瞬间闪烁 */
              .suppress-animations .modal,
              .suppress-animations .modal-dialog,
              .suppress-animations .modal-backdrop {
                transition: none !important;
                animation: none !important;
              }
            `;
            document.head.appendChild(style);
        };

        const setSuppressed = (enable) => {
            ensureSuppressionStyles();
            // 优先调用全局的 toggleSuppression 以统一来源
            if (typeof window.toggleSuppression === 'function') {
                try { window.toggleSuppression(!!enable); return; } catch (e) {}
            }
            const root = document.documentElement;
            if (enable) root.classList.add('suppress-animations');
            else root.classList.remove('suppress-animations');
        };

        const isSuppressedContext = () => {
            try {
                return (
                    document.body.classList.contains('modal-open') ||
                    !!document.querySelector('.modal.show') ||
                    !!document.querySelector('#assetLogsContainer, .asset-logs, .related-logs, .asset-log, .asset-log-modal, .log-item')
                );
            } catch (e) { return false; }
        };

        // 初始化应用一次
        setSuppressed(isSuppressedContext());

        // 若 admin_custom.js 已提供全局抑制开关，则避免重复绑定事件（交由其统一管理）
        if (typeof window.toggleSuppression === 'function') {
            // 已应用一次即可，后续交由 admin_custom.js 的监听器处理
            return;
        }

        // 与 Bootstrap 事件对齐（仅在无全局抑制时绑定）
        document.addEventListener('show.bs.modal', () => {
            setSuppressed(true);
        }, { passive: true });
        document.addEventListener('hide.bs.modal', () => {
            setTimeout(() => setSuppressed(isSuppressedContext()), 60);
        }, { passive: true });
    }

    /**
     * 设置页面动画效果
     */
    setupAnimations() {
        // 为页面元素添加淡入动画
        const animateElements = document.querySelectorAll('.stats-card, .management-module, .quick-link');
        
        animateElements.forEach((element, index) => {
            element.style.opacity = '0';
            element.style.transform = 'translateY(20px)';
            
            setTimeout(() => {
                element.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
                element.style.opacity = '1';
                element.style.transform = 'translateY(0)';
            }, index * 100 + 200);
        });

        // 为导航菜单项添加渐进动画
        this.animateNavigationItems();
    }

    /**
     * 导航菜单项渐进动画
     */
    animateNavigationItems() {
        const navItems = document.querySelectorAll('#nav-sidebar .nav-sidebar ul li');
        
        navItems.forEach((item, index) => {
            item.style.opacity = '0';
            item.style.transform = 'translateX(-20px)';
            
            setTimeout(() => {
                item.style.transition = 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)';
                item.style.opacity = '1';
                item.style.transform = 'translateX(0)';
            }, index * 50 + 300);
        });
    }

    /**
     * 设置交互效果
     */
    setupInteractions() {
        // 卡片悬停效果增强
        this.enhanceCardHoverEffects();
        
        // 按钮点击波纹效果
        this.setupRippleEffect();
        
        // 表单输入框增强
        this.enhanceFormInputs();
        
        // 工具提示
        this.setupTooltips();
    }

    /**
     * 增强卡片悬停效果
     */
    enhanceCardHoverEffects() {
        const cards = document.querySelectorAll('.stats-card, .management-module, .quick-link');
        
        // 在包含日志区域或任意模态框打开时禁用3D鼠标跟随效果，避免频繁重绘导致闪烁
        const isSuppressedContext = () => {
            return (
                !!document.querySelector('#assetLogsContainer, .asset-logs, .related-logs, .asset-log, .asset-log-modal, .log-item') ||
                document.body.classList.contains('modal-open') ||
                !!document.querySelector('.modal.show')
            );
        };
        
        cards.forEach(card => {
            // 鼠标进入
            card.addEventListener('mouseenter', (e) => {
                if (isSuppressedContext()) return;
                e.target.style.transform = 'translateY(-8px) scale(1.02)';
                e.target.style.boxShadow = '0 20px 40px rgba(0, 0, 0, 0.1)';
                // 提示浏览器优化后续 transform，减少重绘
                e.target.style.willChange = 'transform';
            }, { passive: true });
            
            // 鼠标离开
            card.addEventListener('mouseleave', (e) => {
                e.target.style.transform = 'translateY(0) scale(1)';
                e.target.style.boxShadow = '';
                e.target.style.willChange = '';
            }, { passive: true });
            
            // 添加微妙的3D效果（使用 rAF 节流，日志页面禁用）
            let ticking = false;
            card.addEventListener('mousemove', (e) => {
                if (isSuppressedContext()) return; // 日志页面或模态框打开时禁用
                if (ticking) return;
                ticking = true;
                window.requestAnimationFrame(() => {
                    const rect = card.getBoundingClientRect();
                    const centerX = rect.left + rect.width / 2;
                    const centerY = rect.top + rect.height / 2;
                    const deltaX = (e.clientX - centerX) / rect.width;
                    const deltaY = (e.clientY - centerY) / rect.height;
                    const rotateX = deltaY * -8; // 略微降低旋转幅度
                    const rotateY = deltaX * 8;
                    card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-8px) scale(1.02)`;
                    ticking = false;
                });
            }, { passive: true });
        });
    }

    /**
     * 设置按钮波纹效果
     */
    setupRippleEffect() {
        const buttons = document.querySelectorAll('.button, .btn, input[type="submit"], input[type="button"]');
        const isSuppressedContext = () => (
            document.body.classList.contains('modal-open') ||
            !!document.querySelector('.modal.show') ||
            !!document.querySelector('#assetLogsContainer, .asset-logs, .related-logs, .asset-log, .asset-log-modal, .log-item')
        );

        buttons.forEach(button => {
            button.addEventListener('click', (e) => {
                if (isSuppressedContext()) return; // 模态或日志上下文禁用波纹，避免闪烁
                const rect = button.getBoundingClientRect();
                const ripple = document.createElement('span');
                const size = Math.max(rect.width, rect.height);
                const x = e.clientX - rect.left - size / 2;
                const y = e.clientY - rect.top - size / 2;
                
                ripple.style.cssText = `
                    position: absolute;
                    border-radius: 50%;
                    background: rgba(255, 255, 255, 0.5);
                    transform: scale(0);
                    animation: ripple 0.6s linear;
                    left: ${x}px;
                    top: ${y}px;
                    width: ${size}px;
                    height: ${size}px;
                    pointer-events: none;
                `;
                
                // 确保按钮有相对定位
                if (getComputedStyle(button).position === 'static') {
                    button.style.position = 'relative';
                }
                
                button.style.overflow = 'hidden';
                button.appendChild(ripple);
                
                // 动画结束后移除元素
                setTimeout(() => {
                    ripple.remove();
                }, 600);
            });
        });
        
        // 添加波纹动画CSS
        if (!document.querySelector('#ripple-styles')) {
            const rippleStyles = document.createElement('style');
            rippleStyles.id = 'ripple-styles';
            rippleStyles.textContent = `
                @keyframes ripple {
                    to {
                        transform: scale(2);
                        opacity: 0;
                    }
                }
            `;
            document.head.appendChild(rippleStyles);
        }
    }

    /**
     * 增强表单输入框
     */
    enhanceFormInputs() {
        const inputs = document.querySelectorAll('input[type="text"], input[type="email"], input[type="password"], textarea, select');
        
        const isSuppressedContext = () => {
            return (
                document.body.classList.contains('modal-open') ||
                !!document.querySelector('.modal.show') ||
                !!document.querySelector('#assetLogsContainer, .asset-logs, .related-logs, .asset-log, .asset-log-modal, .log-item')
            );
        };
        
        inputs.forEach(input => {
            // 获得焦点时的效果
            input.addEventListener('focus', () => {
                input.style.borderColor = 'var(--primary)';
                input.style.boxShadow = '0 0 0 3px rgba(37, 99, 235, 0.1)';
                if (!isSuppressedContext()) {
                    input.style.transform = 'translateY(-2px)';
                    input.style.willChange = 'transform, box-shadow';
                }
            });
            
            // 失去焦点时的效果
            input.addEventListener('blur', () => {
                input.style.borderColor = '';
                input.style.boxShadow = '';
                input.style.transform = '';
                input.style.willChange = '';
            });
        });
    }

    /**
     * 设置工具提示
     */
    setupTooltips() {
        const elementsWithTooltips = document.querySelectorAll('[title]');
        
        elementsWithTooltips.forEach(element => {
            const title = element.getAttribute('title');
            element.removeAttribute('title');
            
            let tooltip = null;
            
            element.addEventListener('mouseenter', (e) => {
                tooltip = document.createElement('div');
                tooltip.textContent = title;
                tooltip.style.cssText = `
                    position: absolute;
                    background: var(--gray-900);
                    color: white;
                    padding: 0.5rem 0.75rem;
                    border-radius: 0.375rem;
                    font-size: 0.875rem;
                    z-index: 10000;
                    pointer-events: none;
                    white-space: nowrap;
                    opacity: 0;
                    transform: translateY(10px);
                    transition: all 0.2s ease;
                `;
                
                document.body.appendChild(tooltip);
                
                // 定位工具提示
                const rect = element.getBoundingClientRect();
                const tooltipRect = tooltip.getBoundingClientRect();
                
                tooltip.style.left = `${rect.left + rect.width / 2 - tooltipRect.width / 2}px`;
                tooltip.style.top = `${rect.bottom + 8}px`;
                
                // 显示动画
                setTimeout(() => {
                    tooltip.style.opacity = '1';
                    tooltip.style.transform = 'translateY(0)';
                }, 10);
            });
            
            element.addEventListener('mouseleave', () => {
                if (tooltip) {
                    tooltip.style.opacity = '0';
                    tooltip.style.transform = 'translateY(10px)';
                    setTimeout(() => {
                        if (tooltip && tooltip.parentNode) {
                            tooltip.remove();
                        }
                    }, 200);
                }
            });
        });
    }

    /**
     * 设置移动端菜单
     */
    setupMobileMenu() {
        if (window.innerWidth <= 768) {
            this.createMobileMenuButton();
        }
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            if (window.innerWidth <= 768) {
                this.createMobileMenuButton();
            } else {
                this.removeMobileMenuButton();
            }
        });
    }

    createMobileMenuButton() {
        if (document.querySelector('.mobile-menu-toggle')) return;
        
        const toggleBtn = document.createElement('button');
        toggleBtn.className = 'mobile-menu-toggle';
        toggleBtn.innerHTML = '<i class="fas fa-bars"></i>';
        toggleBtn.setAttribute('aria-label', '菜单');
        
        const overlay = document.createElement('div');
        overlay.className = 'menu-overlay';
        
        document.body.appendChild(toggleBtn);
        document.body.appendChild(overlay);
        
        const sidebar = document.getElementById('nav-sidebar');
        
        toggleBtn.addEventListener('click', () => {
            const isOpen = sidebar.classList.contains('show');
            
            if (isOpen) {
                this.closeMobileMenu();
            } else {
                this.openMobileMenu();
            }
        });
        
        overlay.addEventListener('click', () => {
            this.closeMobileMenu();
        });
        
        // ESC键关闭菜单
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && sidebar.classList.contains('show')) {
                this.closeMobileMenu();
            }
        });
    }

    openMobileMenu() {
        const sidebar = document.getElementById('nav-sidebar');
        const overlay = document.querySelector('.menu-overlay');
        const toggleBtn = document.querySelector('.mobile-menu-toggle');
        
        sidebar.classList.add('show');
        overlay.classList.add('show');
        toggleBtn.innerHTML = '<i class="fas fa-times"></i>';
        
        // 禁用背景滚动
        document.body.style.overflow = 'hidden';
    }

    closeMobileMenu() {
        const sidebar = document.getElementById('nav-sidebar');
        const overlay = document.querySelector('.menu-overlay');
        const toggleBtn = document.querySelector('.mobile-menu-toggle');
        
        sidebar.classList.remove('show');
        overlay.classList.remove('show');
        toggleBtn.innerHTML = '<i class="fas fa-bars"></i>';
        
        // 恢复背景滚动
        document.body.style.overflow = '';
    }

    removeMobileMenuButton() {
        const toggleBtn = document.querySelector('.mobile-menu-toggle');
        const overlay = document.querySelector('.menu-overlay');
        const sidebar = document.getElementById('nav-sidebar');
        
        if (toggleBtn) toggleBtn.remove();
        if (overlay) overlay.remove();
        if (sidebar) sidebar.classList.remove('show');
        
        // 恢复背景滚动
        document.body.style.overflow = '';
    }

    /**
     * 设置键盘快捷键
     */
    setupKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // Ctrl/Cmd + K: 快速搜索
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                this.focusSearchInput();
            }
            
            // Alt + M: 切换移动端菜单
            if (e.altKey && e.key === 'm') {
                e.preventDefault();
                const sidebar = document.getElementById('nav-sidebar');
                if (window.innerWidth <= 768) {
                    if (sidebar.classList.contains('show')) {
                        this.closeMobileMenu();
                    } else {
                        this.openMobileMenu();
                    }
                }
            }
        });
    }

    focusSearchInput() {
        const searchInput = document.querySelector('input[type="search"], input[name="q"], .search-input');
        if (searchInput) {
            searchInput.focus();
            searchInput.select();
        }
    }

    /**
     * 设置平滑滚动
     */
    setupSmoothScrolling() {
        // 为所有内部链接添加平滑滚动
        const internalLinks = document.querySelectorAll('a[href^="#"]');
        
        internalLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                const targetId = link.getAttribute('href').substring(1);
                const targetElement = document.getElementById(targetId);
                
                if (targetElement) {
                    e.preventDefault();
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    }

    /**
     * 设置加载状态
     */
    setupLoadingStates() {
        // 为表单提交添加加载状态
        const forms = document.querySelectorAll('form');
        
        forms.forEach(form => {
            form.addEventListener('submit', (e) => {
                const submitButton = form.querySelector('input[type="submit"], button[type="submit"]');
                
                if (submitButton) {
                    const originalText = submitButton.textContent || submitButton.value;
                    submitButton.disabled = true;
                    
                    if (submitButton.tagName === 'BUTTON') {
                        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
                    } else {
                        submitButton.value = '处理中...';
                    }
                    
                    // 5秒后恢复按钮状态（防止意外情况）
                    setTimeout(() => {
                        submitButton.disabled = false;
                        if (submitButton.tagName === 'BUTTON') {
                            submitButton.textContent = originalText;
                        } else {
                            submitButton.value = originalText;
                        }
                    }, 5000);
                }
            });
        });
    }

    /**
     * 设置搜索功能增强
     */
    setupSearchEnhancements() {
        // 创建搜索容器
        this.createEnhancedSearch();
        
        // 设置搜索输入框增强
        this.enhanceSearchInputs();
        
        // 设置快捷搜索
        this.setupQuickSearch();
    }
    
    createEnhancedSearch() {
        const header = document.getElementById('header');
        if (!header || document.querySelector('.search-container')) return;
        
        const searchContainer = document.createElement('div');
        searchContainer.className = 'search-container';
        searchContainer.innerHTML = `
            <div class="search-form">
                <div class="search-input-group">
                    <input type="text" class="search-input" placeholder="请输入资产名称、用户姓名或部门名称..." id="globalSearch">
                    <i class="fas fa-search search-icon"></i>
                </div>
                <div class="search-filters">
                    <button class="search-filter-btn active" data-filter="all">
                        <i class="fas fa-globe"></i>
                        全部
                    </button>
                    <button class="search-filter-btn" data-filter="assets">
                        <i class="fas fa-laptop"></i>
                        资产
                    </button>
                    <button class="search-filter-btn" data-filter="users">
                        <i class="fas fa-users"></i>
                        用户
                    </button>
                    <button class="search-filter-btn" data-filter="departments">
                        <i class="fas fa-building"></i>
                        部门
                    </button>
                </div>
            </div>
        `;
        
        // 在内容区域开始处插入搜索容器
        const content = document.querySelector('.content');
        if (content) {
            content.insertBefore(searchContainer, content.firstChild);
        }
        
        // 绑定搜索事件
        this.bindSearchEvents();
    }
    
    bindSearchEvents() {
        const searchInput = document.getElementById('globalSearch');
        const filterBtns = document.querySelectorAll('.search-filter-btn');
        
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.handleSearch(e.target.value);
            });
            
            searchInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    this.performSearch(e.target.value);
                }
            });
        }
        
        filterBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                filterBtns.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                
                const filter = btn.dataset.filter;
                this.setSearchFilter(filter);
            });
        });
    }
    
    handleSearch(query) {
        // 实时搜索提示
        if (query.length > 2) {
            console.log('搜索:', query);
            // 这里可以添加实时搜索结果显示
        }
    }
    
    performSearch(query) {
        console.log('执行搜索:', query);
        this.showNotification('搜索', `正在搜索 "${query}"...`, 'info');
        
        // 这里可以添加实际的搜索逻辑
    }
    
    setSearchFilter(filter) {
        console.log('设置搜索过滤器:', filter);
        
        const filterNames = {
            all: '全部',
            assets: '资产',
            users: '用户',
            departments: '部门'
        };
        
        this.showNotification('过滤器', `已切换到 ${filterNames[filter]} 过滤器`, 'info');
    }

    /**
     * 设置导航高亮
     */
    setupNavigationHighlight() {
        const currentUrl = window.location.pathname;
        const navLinks = document.querySelectorAll('#nav-sidebar .nav-sidebar ul li a:not(.addlink)');
        
        navLinks.forEach(link => {
            // 移除之前的高亮状态
            link.classList.remove('current', 'selected');
            
            // 检查是否为当前页面
            if (link.getAttribute('href') === currentUrl) {
                link.classList.add('current');
            }
        });
        
        // 为导航链接添加点击事件
        navLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                // 移除所有高亮
                navLinks.forEach(l => l.classList.remove('current', 'selected'));
                // 高亮当前点击的链接
                link.classList.add('current');
                
                // 显示加载状态
                this.showPageLoadingState(link.textContent.trim());
            });
        });
    }
    
    showPageLoadingState(pageName) {
        // 显示页面加载状态
        const loadingIndicator = document.createElement('div');
        loadingIndicator.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--primary), var(--primary-light));
            z-index: 10001;
            animation: loadingProgress 1s ease-out;
        `;
        
        document.body.appendChild(loadingIndicator);
        
        // 添加加载动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes loadingProgress {
                0% { transform: translateX(-100%); }
                100% { transform: translateX(0); }
            }
        `;
        document.head.appendChild(style);
        
        // 1秒后移除加载指示器
        setTimeout(() => {
            loadingIndicator.remove();
            style.remove();
        }, 1000);
        
        this.showNotification('页面切换', `正在加载 ${pageName} 页面...`, 'info');
    }

    /**
     * 触发主题加载完成事件
     */
    triggerThemeLoadedEvent() {
        const event = new CustomEvent('minimalThemeLoaded', {
            detail: {
                version: '6.0.0',
                theme: 'minimal-fashion',
                timestamp: new Date().toISOString()
            }
        });
        
        document.dispatchEvent(event);
    }

    /**
     * 显示通知消息
     */
    showNotification(title, message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        
        const colors = {
            info: 'var(--primary)',
            success: 'var(--success)',
            warning: 'var(--warning)',
            error: 'var(--danger)'
        };
        
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-left: 4px solid ${colors[type]};
            border-radius: 0.5rem;
            padding: 1rem 1.5rem;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            z-index: 10000;
            max-width: 400px;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        `;
        
        notification.innerHTML = `
            <div style="display: flex; align-items: flex-start; gap: 0.75rem;">
                <div style="flex-shrink: 0; color: ${colors[type]};">
                    <i class="fas fa-${type === 'error' ? 'exclamation-triangle' : type === 'success' ? 'check' : type === 'warning' ? 'exclamation-circle' : 'info-circle'}"></i>
                </div>
                <div style="flex: 1;">
                    <div style="font-weight: 600; color: var(--gray-900); margin-bottom: 0.25rem;">${title}</div>
                    <div style="color: var(--gray-600); font-size: 0.875rem;">${message}</div>
                </div>
                <button style="background: none; border: none; color: var(--gray-400); cursor: pointer; padding: 0; font-size: 1.125rem;" onclick="this.parentNode.parentNode.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 10);
        
        // 3秒后自动消失
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 300);
        }, 3000);
    }

    /**
     * 设置侧边栏控制功能
     */
    setupSidebarControls() {
        this.createSidebarToggleButton();
        this.setupSidebarEvents();
    }
    
    /**
     * 创建侧边栏切换按钮
     */
    createSidebarToggleButton() {
        if (document.querySelector('.sidebar-toggle-btn')) return;
        
        const toggleBtn = document.createElement('button');
        toggleBtn.className = 'sidebar-toggle-btn';
        toggleBtn.innerHTML = '<i class="fas fa-bars"></i>';
        toggleBtn.title = '切换菜单栏';
        
        const mainElement = document.querySelector('.main');
        if (mainElement) {
            mainElement.appendChild(toggleBtn);
        }
        
        toggleBtn.addEventListener('click', () => {
            this.toggleSidebar();
        });
        
        this.createSidebarCollapseButton();
    }
    
    /**
     * 创建侧边栏内部收起按钮
     */
    createSidebarCollapseButton() {
        const sidebar = document.getElementById('nav-sidebar');
        if (!sidebar || sidebar.querySelector('.sidebar-collapse-btn')) return;
        
        const collapseBtn = document.createElement('button');
        collapseBtn.className = 'sidebar-collapse-btn';
        collapseBtn.innerHTML = '<i class="fas fa-angle-left"></i>';
        collapseBtn.title = '收起菜单栏';
        
        sidebar.appendChild(collapseBtn);
        
        collapseBtn.addEventListener('click', () => {
            this.collapseSidebar();
        });
    }
    
    /**
     * 切换侧边栏状态
     */
    toggleSidebar() {
        const sidebar = document.getElementById('nav-sidebar');
        
        switch (this.sidebarState) {
            case 'normal':
                this.expandSidebar();
                break;
            case 'expanded':
                this.collapseSidebar();
                break;
            case 'collapsed':
                this.normalSidebar();
                break;
        }
    }
    
    /**
     * 展开侧边栏
     */
    expandSidebar() {
        const sidebar = document.getElementById('nav-sidebar');
        const toggleBtn = document.querySelector('.sidebar-toggle-btn');
        
        sidebar.classList.remove('collapsed');
        sidebar.classList.add('expanded');
        toggleBtn.innerHTML = '<i class="fas fa-angle-left"></i>';
        
        this.sidebarState = 'expanded';
        this.updateContentLayout();
        
        this.showNotification('菜单栏', '已展开菜单栏，获得更大的操作空间', 'info');
    }
    
    /**
     * 收起侧边栏
     */
    collapseSidebar() {
        const sidebar = document.getElementById('nav-sidebar');
        const toggleBtn = document.querySelector('.sidebar-toggle-btn');
        
        sidebar.classList.remove('expanded');
        sidebar.classList.add('collapsed');
        toggleBtn.innerHTML = '<i class="fas fa-angle-right"></i>';
        
        this.sidebarState = 'collapsed';
        this.updateContentLayout();
        
        this.showNotification('菜单栏', '已收起菜单栏，获得更大的内容空间', 'info');
    }
    
    /**
     * 恢复正常侧边栏
     */
    normalSidebar() {
        const sidebar = document.getElementById('nav-sidebar');
        const toggleBtn = document.querySelector('.sidebar-toggle-btn');
        
        sidebar.classList.remove('expanded', 'collapsed');
        toggleBtn.innerHTML = '<i class="fas fa-bars"></i>';
        
        this.sidebarState = 'normal';
        this.updateContentLayout();
    }
    
    /**
     * 更新内容布局
     */
    updateContentLayout() {
        const root = document.documentElement;
        
        switch (this.sidebarState) {
            case 'expanded':
                root.style.setProperty('--content-margin-dynamic', 'var(--sidebar-width-expanded)');
                break;
            case 'collapsed':
                root.style.setProperty('--content-margin-dynamic', 'var(--sidebar-width-collapsed)');
                break;
            default:
                root.style.setProperty('--content-margin-dynamic', 'var(--sidebar-width)');
                break;
        }
    }
    
    /**
     * 设置侧边栏事件
     */
    setupSidebarEvents() {
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.altKey && e.key === 's') {
                e.preventDefault();
                this.toggleSidebar();
            }
        });
        
        // 双击标题展开/收起
        const titles = document.querySelectorAll('#nav-sidebar h2');
        titles.forEach(title => {
            title.addEventListener('dblclick', () => {
                this.toggleSidebar();
            });
            title.style.cursor = 'pointer';
            title.title = '双击切换菜单栏大小';
        });
    }
    
    /**
     * 设置响应式布局
     */
    setupResponsiveLayout() {
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            const width = window.innerWidth;
            
            if (width <= 768 && this.sidebarState !== 'mobile') {
                this.sidebarState = 'mobile';
            } else if (width > 768 && this.sidebarState === 'mobile') {
                this.normalSidebar();
            }
        });
    }
    getThemeInfo() {
        return {
            name: 'Minimal Fashion',
            version: '6.0.0',
            isLoaded: this.isLoaded,
            features: [
                'Modern minimal design',
                'Smooth animations',
                'Mobile responsive',
                'Interactive effects',
                'Keyboard shortcuts',
                'Loading states'
            ]
        };
    }
}

// 自动初始化主题增强器
const minimalTheme = new MinimalThemeEnhancer();

// 全局访问
window.minimalTheme = minimalTheme;

// 主题加载完成后的回调
document.addEventListener('minimalThemeLoaded', (e) => {
    console.log('🎉 时尚简约主题加载完成!', e.detail);
    
    // 显示欢迎通知
    setTimeout(() => {
        minimalTheme.showNotification(
            '主题已激活',
            '时尚简约主题已成功加载，享受现代化的管理体验！',
            'success'
        );
    }, 1000);
});

console.log('✨ 时尚简约主题增强器已准备就绪');